using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace XwingGame
{

    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class XwingGame : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        private Bee bee;
        private Camera camera;
        private KeyboardState lastKeyboardState;
        private SpriteFont scoreFont;

        public float score = 0;
        public AsteroidField asteroidField;

        public Camera Camera { get { return camera; } }
        public AsteroidField AsteroidField { get { return asteroidField; } }
        public Bee Bee { get { return bee; } }
        public SoundBank SoundBank { get { return soundBank; } }

        /// <summary>
        /// A reference to the audio engine we use
        /// </summary>
        AudioEngine audioEngine;
 
        /// <summary>
        /// The loaded audio wave bank
        /// </summary>
        WaveBank waveBank;

        /// <summary>
        /// The loaded audio sound bank
        /// </summary>
        SoundBank soundBank;

        public XwingGame()
        {
            graphics = new GraphicsDeviceManager(this);
            bee = new Bee(this);
            camera = new Camera(graphics);
            asteroidField = new AsteroidField(this);
            Content.RootDirectory = "Content";
        }



        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            camera.Initialize();
            lastKeyboardState = Keyboard.GetState();
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            bee.LoadContent(Content);
            asteroidField.LoadContent(Content);
            audioEngine = new AudioEngine("Content\\XwingAudio.xgs");
            waveBank = new WaveBank(audioEngine, "Content\\Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, "Content\\Sound Bank.xsb");
            scoreFont = Content.Load<SpriteFont>("scorefont");
            asteroidField.CreateAsteroids(12);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            KeyboardState keyboardState = Keyboard.GetState();
            if (keyboardState.IsKeyDown(Keys.A) && lastKeyboardState.IsKeyUp(Keys.A))
            {
                bee.Animate = !bee.Animate;
            }

            lastKeyboardState = keyboardState;


            ///
            /// Ship accelerating when E is pressed
            ///
            if (keyboardState.IsKeyDown(Keys.E))
                bee.Thrust = 1;
            else
                bee.Thrust = 0;

            ///
            ///  Ship turning when left and right are pressed
            ///
            if (keyboardState.IsKeyDown(Keys.Left))
            {
                bee.TurnRate = 1;
            }
            else if (keyboardState.IsKeyDown(Keys.Right))
            {
                bee.TurnRate = -1;
            }
            else
            {
                bee.TurnRate = 0;
            }


            ///
            /// Ship pitching when Up and Down are pressed.
            ///
            if (keyboardState.IsKeyDown(Keys.Up))
            {
                bee.PitchRate = -1;
            }
            else if (keyboardState.IsKeyDown(Keys.Down))
            {
                bee.PitchRate = 1;
            }
            else
            {
                bee.PitchRate = 0;
            }


            bee.Update(gameTime);
            asteroidField.Update(gameTime);
            camera.Update(gameTime);
            camera.Center = bee.Position;
            camera.DesiredEye = Vector3.Transform(new Vector3(0, 500, -2677), bee.Transform);
            camera.DesiredUp = bee.Transform.Up;
            audioEngine.Update();
            base.Update(gameTime);

//            System.Diagnostics.Trace.WriteLine(camera.Up.ToString());
//            System.Diagnostics.Trace.WriteLine(xwing.Transform.Up.ToString());
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            string scoreString = String.Format("{0:0000}", score);
            GraphicsDevice.Clear(Color.GreenYellow);
            bee.Draw(graphics, gameTime);
            asteroidField.Draw(graphics, gameTime);
            spriteBatch.Begin();
            spriteBatch.DrawString(scoreFont, scoreString, new Vector2(10, 10), Color.AntiqueWhite);
            spriteBatch.End();
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            base.Draw(gameTime);
        }

        public void Reset()
        {
            SoundBank.PlayCue("explosion3");
            score /= 2;
            asteroidField.Reset();
        }
    }
}
